package com.linjiahao.nettyTwo.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linjiahao.nettyTwo.constant.HandlerServiceName;
import com.linjiahao.nettyTwo.vo.ChatMessage;
import com.linjiahao.servicebase.common.RabbitPublisher;
import com.linjiahao.servicebase.common.RedisService;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @ClassName WebSockerHandler
 * @Description: 自定义业务handler
 * @Author linjiahao
 * @Date 23/12/2021
 **/
@Component
@Slf4j
@ChannelHandler.Sharable
public class WebSockerHandler extends SimpleChannelInboundHandler<Object> {


    @Resource
    private RedisService redisService;

    @Resource
    private RabbitPublisher rabbitPublisher;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("与客户端建立连接，通道开启,id:{}", ctx.channel().id());
        ChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("与客户端断开连接，通道关闭,id:{}", ctx.channel().id());
        ChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object message) {
        if (message instanceof FullHttpRequest){
            //以http请求形式接入，但是走的是websocket,首次需要鉴权
            HandlerServiceFactory.getHandlerService(HandlerServiceName.AUTH_HANDLER.getName()).
                    handlerWebsocket(ctx,message);
        }else if (message instanceof TextWebSocketFrame){
            //处理websocket客户端的消息
            JSONObject jsonObject = JSON.parseObject(((TextWebSocketFrame) message).text());
            log.info("接收到的消息为:{}",jsonObject.toJSONString());
            String userId = jsonObject.getString("userId");
            String receiverId = jsonObject.getString("receiverId");
            String sendMessage = jsonObject.getString("message");
            Object channleId = redisService.hget(ChannelHandlerPool.channelUserKey, receiverId);
            Channel channel = null;
            if(channleId!=null){
                channel = ChannelHandlerPool.channelGroup.find((ChannelId)channleId);
            }
            if(channel!=null){
                channel.writeAndFlush(new TextWebSocketFrame(sendMessage));
            }else {
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setUserId(userId);
                chatMessage.setReceiverId(receiverId);
                chatMessage.setMessage(sendMessage);
                chatMessage.setMessageId(UUID.randomUUID().toString());
                chatMessage.setChannelId(channleId);
                redisService.hset(ChannelHandlerPool.userMessageKey,receiverId,JSON.toJSONString(chatMessage));
                rabbitPublisher.send(JSON.toJSONString(chatMessage));
            }
            ctx.channel().writeAndFlush(new TextWebSocketFrame("发送成功"));
        }

    }



}
